package cn.com.edu.nju.ecrec.dataProcess;

import java.util.List;

import javax.persistence.EntityManager;

import cn.com.edu.nju.ecrec.dao.*;
import cn.com.edu.nju.ecrec.model.*;
import cn.com.edu.nju.ecrec.util.DaoName;
import cn.com.edu.nju.ecrec.util.JPAFactory;

public class UserItemExtraction {

	static void processUserItem() {
		try {
			UserInfoDao uid = DaoFactory.getInstance().getDao(DaoName.USER_INFO_DAO);
			ItemDao id = DaoFactory.getInstance().getDao(DaoName.ITEM_DAO);
			EventDao ed = DaoFactory.getInstance().getDao(DaoName.EVENT_DAO);
			EntityManager em = JPAFactory.getManager();
			
			List<String> uri_names = id.getUriNames();
			for(String uri_name : uri_names){
				if(!(uri_name.equals("")||uri_name==null)){
					List<String> userIDs = ed.getUserIDsByUriName(uri_name);
					Item i = id.getByUriName(uri_name);
					if(i != null && !userIDs.isEmpty()){
						List<UserInfo> uis = uid.getByUserIDs(userIDs);
						for(UserInfo ui : uis){
							UserItem useritem = new UserItem();
							useritem.setInfoID(ui.getInfoID());
							useritem.setPid(i.getPid());
							em.getTransaction().begin();
							em.persist(useritem);
							em.getTransaction().commit();
						}
					}
				}
			}

			em.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	static void processUserInfoItem(){
		try {
			UserInfoDao uid = DaoFactory.getInstance().getDao(DaoName.USER_INFO_DAO);
			ItemDao id = DaoFactory.getInstance().getDao(DaoName.ITEM_DAO);
			EntityManager em = JPAFactory.getManager();
			
			List<String> uri_names = id.getUriNames();
			for(String uri_name : uri_names){
				if(!(uri_name.equals("")||uri_name==null)){
					Item i = id.getByUriName(uri_name);
					if(i != null){
						List<UserInfo> uis = uid.getByUriName(uri_name);
						for(UserInfo ui : uis){
							UserItem useritem = new UserItem();
							useritem.setInfoID(ui.getInfoID());
							useritem.setPid(i.getPid());
							em.getTransaction().begin();
							em.persist(useritem);
							em.getTransaction().commit();
						}
					}
				}
			}

			em.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		//processUserItem();
		processUserInfoItem();
	}

}
